<template>
  <common-list>
    <common-search slot="search" @search="handleQuery" @reset="resetQuery">
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        @submit.native.prevent
        v-show="showSearch"
        label-width="65px"
      >
        <el-form-item label="任务名称" prop="executionPolicyName">
          <common-input
            v-model="queryParams.executionPolicyName"
            clearable
            @enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="执行周期" prop="executionCycleTypeId">
          <el-select v-model="queryParams.executionCycleTypeId" filterable>
            <el-option label="全部" :value="null"></el-option>
            <el-option
              v-for="item in executionCycleTypeArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="任务状态" prop="taskStatus">
          <el-select v-model="queryParams.taskStatus">
            <el-option label="全部" :value="null"></el-option>
            <el-option label="启用" :value="0" />
            <el-option label="停用" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="资源范围" prop="resourceRange">
          <el-cascader
            style="width: 100%"
            v-model="queryParams.resourceRange"
            :show-all-levels="false"
            :options="resourceScope"
            :props="{
              label: 'name',
              value: 'name',
              emitPath: false,
            }"
            clearable
          >
            <template slot-scope="{ node, data }">
              <common-marquee-text :content="data.name"></common-marquee-text>
            </template>
          </el-cascader>
        </el-form-item>
        <el-form-item label="执行状态" prop="executionStatus">
          <el-select v-model="queryParams.executionStatus">
            <el-option label="全部" :value="null"></el-option>
            <el-option label="正在扫描" :value="1" />
            <el-option label="扫描完成" :value="2" />
            <el-option label="扫描失败" :value="3" />
          </el-select>
        </el-form-item>
        <!-- <common-dept
          ref="commonDept"
          :currentParent="currentParent"
          @getDeptId="getDeptId"
          @getDeptList="getDeptList"
          @getLoading="getLoading"
        ></common-dept> -->
      </el-form>
    </common-search>

    <el-row :gutter="10" class="mb8" slot="tools">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          @click="handleAdd"
          v-hasPermi="['datascan:executionpolicy:add']"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          :disabled="!showBatch"
          @click="handleDelete"
          v-hasPermi="['datascan:executionpolicy:remove']"
          >批量删除
        </el-button>
      </el-col>
      <el-button
        type="success"
        plain
        icon="el-icon-circle-check"
        @click="handleStop(0)"
        v-hasPermi="['datascan:executionpolicy:status']"
        :disabled="this.ids.length === 0 ? true : false"
        >启用
      </el-button>
      <el-button
        type="danger"
        plain
        icon="el-icon-remove-outline"
        @click="handleStop(1)"
        v-hasPermi="['datascan:executionpolicy:status']"
        :disabled="this.ids.length === 0 ? true : false"
        >停用
      </el-button>
    </el-row>

    <common-table
      slot="content"
      v-loading="loading"
      :data="policyList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="任务名称"
        align="left"
        prop="executionPolicyName"
        fixed="left"
        width="200"
        show-tooltip-when-overflow
      />
      <!--      <el-table-column label="行数" align="left" prop="lineNumber" />-->
      <el-table-column
        label="执行周期"
        align="left"
        width="220"
        prop="executionCycleTypeId"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          {{
            executionCycleTypeFn(scope.row.executionCycleTypeId) +
            ((scope.row.executionDay || scope.row.executionDay === 0) &&
            scope.row.executionCycleTypeId === 5
              ? "/" + scope.row.executionDay + "号"
              : "") +
            ((scope.row.executionDay || scope.row.executionDay === 0) &&
            scope.row.executionCycleTypeId === 4
              ? "/" + dayArr[scope.row.executionDay]
              : "") +
            (scope.row.executionTime ? "/" + scope.row.executionTime : "")
          }}
        </template>
      </el-table-column>
      <el-table-column
        label="资源范围"
        align="left"
        prop="resourceRange"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        label="扫描开始时间"
        align="left"
        prop="startTime"
        width="160"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        label="扫描结束时间"
        align="left"
        prop="endTime"
        width="160"
        show-overflow-tooltip
      >
      </el-table-column>
      <!-- <el-table-column
        label="组织"
        align="left"
        prop="deptName"
        width="180"
        show-overflow-tooltip
      /> -->
      <el-table-column label="任务状态" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.taskStatus === 0" type="success">启用</el-tag>
          <el-tag v-if="scope.row.taskStatus === 1" type="danger">停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="left"
        fixed="right"
        class-name="small-padding fixed-width"
        width="186"
      >
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.taskStatus === 0"
            type="text"
            @click="immediateExecuteTask(scope.row)"
            v-hasPermi="['datascan:executionpolicy:excute']"
            >立即执行
          </el-button>

          <el-button
            type="text"
            @click="taskHistoryFn(scope.row)"
            v-hasPermi="['datascan:executionhistory:list']"
          >
            执行历史
          </el-button>

          <el-dropdown @command="handleCommand" trigger="click">
            <span
              class="el-dropdown-link"
              style="cursor: pointer; margin-left: 10px; font-size: 12px"
              :style="{ '--theme-color': systemInfo.theme }"
              v-hasPermi="[
                'datascan:executionpolicy:edit',
                'datascan:executionpolicy:status',
                'datascan:executionpolicy:remove',
              ]"
            >
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="setCommand('detail', scope.row)">
                <span style="font-size: 12px !important"> 详情 </span>
              </el-dropdown-item>
              <el-dropdown-item :command="setCommand('edit', scope.row, 1)">
                <span
                  v-hasPermi="['datascan:executionpolicy:edit']"
                  style="font-size: 12px !important"
                >
                  编辑
                </span>
              </el-dropdown-item>
              <el-dropdown-item :command="setCommand('change', scope.row)">
                <span
                  style="font-size: 12px !important"
                  v-hasPermi="['datascan:executionpolicy:status']"
                >
                  {{ scope.row.taskStatus === 0 ? "停用" : "启用" }}
                </span>
              </el-dropdown-item>
              <el-dropdown-item :command="setCommand('delete', scope.row)">
                <span
                  v-hasPermi="['datascan:executionpolicy:remove']"
                  style="font-size: 12px !important"
                  >删除
                </span>
              </el-dropdown-item>
              <el-dropdown-item
                :command="setCommand('pauseContinues', scope.row)"
                v-hasPermi="['datascan:executionpolicy:pauseContinues']"
              >
                <span style="font-size: 12px !important">
                  {{ scope.row.isPause === 1 ? "暂停" : "继续" }}
                </span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </common-table>

    <pagination
      slot="pagination"
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或编辑执行策略管理对话框 -->
    <common-edit-dialog
      :title="title"
      :visible.sync="open"
      @cancel="cancel"
      @submit="submitForm"
      :buttonLoading="buttonLoading"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="90px"
        class="add"
        @submit.native.prevent
      >
        <el-row :gutter="18">
          <el-col :span="24">
            <el-form-item label="任务名称" prop="executionPolicyName">
              <common-input
                :disabled="isDisabled"
                v-model="form.executionPolicyName"
                placeholder="请输入"
                :maxlength="16"
              />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="扫描时间" prop="executionPolicyTime">
              <el-date-picker
                v-model="form.executionPolicyTime"
                type="datetimerange"
                range-separator="至"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                :default-time="['00:00:00', '23:59:59']"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="库扫描策略" prop="scanType">
              <template>
                <el-radio v-model="form.scanType" label="0"
                  >全量<content-tip
                    :tipType="'statistics_all'"
                    popoverWidth="150"
                  ></content-tip>
                </el-radio>

                <el-radio v-model="form.scanType" label="1"
                  >增量<content-tip
                    :tipType="'statistics_add'"
                    popoverWidth="200"
                  ></content-tip>
                </el-radio>
              </template>
            </el-form-item>
          </el-col>

          <el-col :span="form.tablePolicyType === 1 ? 24 : 12">
            <el-form-item label="表扫描策略" prop="tablePolicyType">
              <template>
                <el-radio
                  v-model="form.tablePolicyType"
                  :label="1"
                  @change="changeRadio"
                  >全量<content-tip
                    :tipType="'table_all'"
                    popoverWidth="150"
                  ></content-tip>
                </el-radio>
                <el-radio
                  v-model="form.tablePolicyType"
                  :label="2"
                  @change="changeRadio"
                  >样本<content-tip
                    :tipType="'statistics_sample'"
                  ></content-tip>
                </el-radio>
              </template>
            </el-form-item>
          </el-col>

          <el-col :span="12" v-if="form.tablePolicyType === 2">
            <el-form-item label="扫描行数" prop="lineNumber">
              <common-input-number
                v-model="form.lineNumber"
                style="width: 100%"
                :max-length="5"
              />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="资源范围" prop="resourceRangeIds">
              <common-input
                disabled
                v-if="title === '编辑任务'"
                v-model="form.resourceRange"
              />

              <el-cascader
                v-else
                ref="taskCascader"
                style="width: 100%"
                v-model="form.resourceRangeIds"
                :show-all-levels="false"
                :options="resourceScope"
                :props="{
                  label: 'name',
                  value: 'id',
                  emitPath: false,
                  multiple: true,
                }"
                @change="handleChange"
                clearable
              >
                <template slot-scope="{ node, data }">
                  <common-marquee-text
                    :content="data.name"
                  ></common-marquee-text>
                </template>
              </el-cascader>

              <!-- <el-select
                v-else
                v-model="form.restaskDbGroupPos"
                multiple
                value-key="value"
                placeholder="请选择"
                :disabled="isDisabled"
                style="width: 100%"
                filterable
                clearable
              >
                <el-option
                  v-for="item in resourceScope"
                  :key="item.id"
                  :label="item.groupName"
                  :value="item.id"
                >
                  <common-option-span
                    :date="{
                      left: item.groupName,
                      right: item.deptName,
                    }"
                    :isOrg="true"
                  >
                  </common-option-span>
                </el-option>
              </el-select> -->
            </el-form-item>
          </el-col>
          <!--
          <el-col :span="24">
            <common-add-dept
              ref="commonAddDept"
              :deptListParams="deptListParams"
              @getCheckedDeptId="getCheckedDeptId"
              :deptId="form.deptId"
            ></common-add-dept>
          </el-col> -->

          <el-col :span="12">
            <div>
              <el-form-item
                label="执行周期"
                prop="executionCycleTypeId"
                style="width: 100% !important"
              >
                <el-select
                  v-model="form.executionCycleTypeId"
                  placeholder="请选择"
                  filterable
                  clearable
                  @change="changeExecutionCycle"
                >
                  <el-option
                    v-for="item in executionCycleTypeArr"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </div>
          </el-col>

          <el-col :span="12" style="display: flex">
            <el-form-item
              prop="executionTime"
              v-if="form.executionCycleTypeId === 2"
              label-width="30px"
              style="width: 100%"
            >
              <el-date-picker
                v-model="form.executionTime"
                type="datetime"
                placeholder="选择执行时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%"
                @change="checkValidate('executionTime')"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item
              prop="executionTime"
              v-if="form.executionCycleTypeId === 3"
              label-width="30px"
              style="width: 100%"
            >
              <el-time-picker
                v-model="form.executionTime"
                :picker-options="{
                  selectableRange: '00:00:00 - 23:59:59',
                }"
                placeholder="请选择时间"
                value-format="HH:mm"
                format="HH:mm"
                @change="checkValidate('executionTime')"
              >
              </el-time-picker>
            </el-form-item>
            <el-form-item
              prop="executionDay"
              v-if="form.executionCycleTypeId === 4"
              label-width="30px"
              style="width: 50%"
            >
              <el-select
                v-model="form.executionDay"
                placeholder="请选择执行日期"
                style="width: 100%"
                @change="checkValidate('executionDay')"
              >
                <el-option label="星期日" :value="0" />
                <el-option label="星期一" :value="1" />
                <el-option label="星期二" :value="2" />
                <el-option label="星期三" :value="3" />
                <el-option label="星期四" :value="4" />
                <el-option label="星期五" :value="5" />
                <el-option label="星期六" :value="6" />
              </el-select>
            </el-form-item>

            <el-form-item
              prop="executionDay"
              v-if="
                form.executionCycleTypeId === 5 ||
                form.executionCycleTypeId === 7
              "
              label-width="30px"
              style="width: 50%"
            >
              <el-select
                v-model="form.executionDay"
                placeholder="请选择"
                style="width: 100%"
                filterable
                clearable
                @change="checkValidate('executionDay')"
              >
                <el-option
                  v-for="item in 31"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>

            <el-form-item
              prop="executionTime"
              v-if="
                form.executionCycleTypeId === 4 ||
                form.executionCycleTypeId === 5 ||
                form.executionCycleTypeId === 7
              "
              label-width="0"
              style="width: 50%"
            >
              <el-time-picker
                v-model="form.executionTime"
                :picker-options="{
                  selectableRange: '00:00:00 - 23:59:59',
                }"
                placeholder="请选择时间"
                value-format="HH:mm"
                format="HH:mm"
                style="width: 100%"
                @change="checkValidate('executionTime')"
              >
              </el-time-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </common-edit-dialog>

    <policy-detail ref="policyDetail"></policy-detail>
    <template v-if="isShowHistory">
      <History
        :executionPolicyName="executionPolicyName"
        :taskId="taskId"
        @close="closeHistory"
      ></History>
    </template>
  </common-list>
</template>

<script>
import {
  listPolicy,
  getPolicy,
  delPolicy,
  addPolicy,
  updatePolicy,
  setTaskStatus,
  dbgroupList,
  querySystemWithDatabase,
  dbInfoList,
  immediateExecuteTask,
  setPause,
} from "@/api/datascan/executionpolicy/policy";
import BaseList from "@/mixins/BaseList";
import { getSingleArray, getFullDept } from "@/utils/util";
import { mapGetters } from "vuex";
import policyDetail from "./components/policyDetail.vue";
import ContentTip from "@/views/analysisCenter/log/ContentTip/index.vue";
import History from "@/views/datascan/executionhistory/index_bak.vue";

export default {
  components: { policyDetail, ContentTip, History },
  name: "Policy",
  mixins: [BaseList],
  watch: {
    "form.executionCycleTypeId"(val, oldVal) {
      if (val === 1) {
        this.rules = this.rules1;
      }
      if (val === 2) {
        this.rules = { ...this.rules1, ...this.rules3 };
      }
      if (val === 4 || val === 5 || val === 7) {
        this.rules = { ...this.rules1, ...this.rules2, ...this.rules3 };
      }
    },
  },
  data() {
    return {
      taskStatus: null,
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      // ids: [],
      // 非单个禁用
      // single: true,
      // 非多个禁用
      // multiple: true,
      key: "executionPolicyId",
      // 显示查询条件
      showSearch: true,
      // 总条数
      total: 0,
      // 执行策略管理表格数据
      policyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      detailsTitle: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        executionPolicyName: null,
        executionPolicyType: null,
        executionCycleTypeId: null,
        executionDay: null,
        executionTime: null,
        lineNumber: null,
        lastExecutionTime: null,
        taskStatus: null,
        activeFlag: null,
        createUserCode: null,
        resourceRange: null,
        startTime: null,
        endTime: null,
        deptIds: null,
        executionStatus: null,
      },
      resourceScope: [], // 资源范围
      dayArr: [
        "星期日",
        "星期一",
        "星期二",
        "星期三",
        "星期四",
        "星期五",
        "星期六",
      ],
      executionCycleTypeArr: [
        {
          label: "定时",
          value: 2,
        },
        {
          label: "按日",
          value: 3,
        },
        {
          label: "按周",
          value: 4,
        },
        {
          label: "按月",
          value: 5,
        },
      ],
      // 表单参数
      form: {
        scanType: "0",
        tablePolicyType: 1,
      },

      // 表单校验
      rules: {},
      rules1: {
        executionPolicyName: [
          { required: true, message: "请输入任务名称", trigger: "blur" },
        ],
        lineNumber: [
          { required: true, message: "请输入扫描行数", trigger: "blur" },
        ],
        executionPolicyTime: [
          { required: true, message: "请选择扫描时间", trigger: "blur" },
        ],
        scanType: [
          { required: true, message: "请选择库扫描策略", trigger: "blur" },
        ],
        tablePolicyType: [
          { required: true, message: "请选择表扫描策略", trigger: "blur" },
        ],
        resourceRangeIds: [
          { required: true, message: "请选择资源范围", trigger: "blur" },
        ],
        taskStatus: [
          { required: true, message: "请选择是否开启", trigger: "blur" },
        ],
        executionCycleTypeId: [
          { required: true, message: "请选择执行周期", trigger: "blur" },
        ],
        // deptId: [{ required: true, message: '请选择组织', trigger: 'blur' }],
      },
      rules2: {
        executionDay: [{ required: true, message: "请选择", trigger: "blur" }],
      },
      rules3: {
        executionTime: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value) {
                if (this.form.executionCycleTypeId === 2) {
                  let now = new Date().getTime();
                  if (new Date(value).getTime() - now > 0) {
                    callback();
                  } else {
                    callback(new Error("执行时间必须大于当前时间"));
                  }
                } else {
                  callback();
                }
              } else {
                callback(new Error("请选择"));
              }
            },
            trigger: "blur",
          },
        ],
      },
      isDisabled: false,
      currentParent: 4,
      singleDeptList: [],
      deptListParams: [],
      isShowHistory: false,
      executionPolicyName: null,
      taskId: null,
    };
  },
  computed: {
    ...mapGetters(["systemInfo"]),
  },
  created() {
    this.rules = this.rules1;
    this.getList();
    this.dbgroupList();
    // this.dbInfoList()
  },
  methods: {
    checkValidate(key) {
      this.$refs["form"].validateField(key);
    },
    getLoading() {
      this.loading = true;
    },
    // getCheckedDeptId(val) {
    //   this.form.deptId = val;
    // },
    // getDeptList(list) {
    //   this.deptListParams = list;
    //   this.singleDeptList = getSingleArray(list);
    //   this.getList();
    // },
    // getDeptId(val) {
    //   this.queryParams.deptIds = val;
    // },
    getDeptName(val) {
      let dept = this.singleDeptList.find((item) => item.id === val.toString());
      if (dept) return getFullDept(dept.fulllabel);
    },
    executionCycleTypeFn(value) {
      let label = "";
      this.executionCycleTypeArr.map((v) => {
        if (v.value === value) {
          label = v.label;
        }
      });
      return label;
    },
    taskDbGroupPosFn(arr, key) {
      let str = [];
      if (arr && arr.length) {
        arr.map((v) => {
          str.push(v[key]);
        });
      }
      return str.join(",");
    },
    /** 查询执行策略管理列表 */
    dbgroupList() {
      querySystemWithDatabase().then((res) => {
        if (res && res.code === 200) {
          this.resourceScope = res.data;
          this.removeChildren(this.resourceScope, true);
        } else {
          this.resourceScope = [];
        }
      });
    },

    removeChildren(typeList, isFirst) {
      let list = typeList || [];
      let level = 0;
      for (let item of list) {
        if (item.children.length === 0) {
          delete item.children;
        } else {
          this.removeChildren(item.children, false);
        }
        if (isFirst) {
          item.id = level;
          level++;
        }
      }
    },

    // dbInfoList () {
    //   dbInfoList({ status: 0 }).then(res => {
    //     if (res && res.data && res.data.dataList) {
    //       this.resourceScope = res.data.dataList
    //     }
    //   });
    // },
    getList() {
      this.loading = true;
      console.log(this.form.scanType);
      listPolicy(this.queryParams)
        .then((res) => {
          if (res && res.data && res.data.dataList) {
            this.policyList = res.data.dataList.reduce((r, c) => {
              r.push({
                ...c,
                deptName: this.getDeptName(c.deptId || ""),
              });
              return r;
            }, []);
            this.total = res.data.totalCount;
          } else {
            this.policyList = [];
            this.total = 0;
            this.handleListTips(res);
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    immediateExecuteTask(row) {
      this.$confirm("您确认要执行选择的任务吗?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        immediateExecuteTask({
          executionPolicyId: row.executionPolicyId,
        }).then((res) => {
          if (res && res.code === 200) {
            // this.$router.push({
            //   path: "/datahandlerservice/taskplan/executionhistory",
            // });
            this.$GlobalSuccessMessage("执行成功");
          } else {
            this.$GlobalErrorConfirm("执行失败", res.msg);
          }
        });
      });
    },
    taskHistoryFn(row) {
      this.taskId = row.executionPolicyId;
      this.isShowHistory = true;

      // this.$router.push({
      //   path: "/datahandlerservice/taskplan/executionhistory",
      //   query: { executionPolicyName: row.executionPolicyName },
      // });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        executionPolicyId: undefined,
        executionPolicyName: undefined,
        executionPolicyType: undefined,
        executionCycleTypeId: undefined,
        executionDay: undefined,
        executionTime: undefined,
        // lineNumber: undefined,
        lastExecutionTime: undefined,
        taskStatus: 0,
        remark: undefined,
        activeFlag: undefined,
        createUserCode: undefined,
        createTime: undefined,
        scanType: "0",
        tablePolicyType: 1,
        deptId: undefined,
        resourceRangeIds: null,
        restaskDbGroupPos: null,
      };
      this.resetForm("form");
    },
    changeExecutionCycle(val) {
      if (val === 2) {
        this.form.executionTime = null;
      }
    },
    /** 查询按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = this.$options.data().queryParams;
    },
    // 多选框选中数据
    // handleSelectionChange(selection) {
    //   this.ids = selection.map(item => item.executionPolicyId)
    //   this.single = selection.length !== 1
    //   this.multiple = !selection.length
    // },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isDisabled = false;
      this.title = "新增任务";
    },
    handleUpdate(row, n) {
      // 1:编辑  2详情
      if (n === 1) {
        // 0 启用  1停用
        if (row.taskStatus === 0) {
          this.$GlobalErrorConfirm("警告", "启用状态不允许编辑");
        } else {
          this.getPolicy(row, n);
        }
      } else {
        this.getPolicy(row, n);
      }
    },
    getPolicy(row, n) {
      const params = {
        executionPolicyId: row.executionPolicyId,
      };
      getPolicy(params).then((res) => {
        if (res && res.code === 200) {
          this.reset();

          let resourceRangeIds = [];
          if (
            res.data &&
            res.data.taskDbGroupPos &&
            res.data.taskDbGroupPos.length
          ) {
            res.data.taskDbGroupPos.map((v) => {
              resourceRangeIds.push(v.dbGroupId);
            });
          }
          let executionPolicyTime = [];
          if (res.data.startTime && res.data.endTime) {
            executionPolicyTime[0] = res.data.startTime;
            executionPolicyTime[1] = res.data.endTime;
          }

          this.isDisabled = res.data.isExecuted != "0";

          this.form = Object.assign({}, res.data, {
            resourceRangeIds: res.data.resourceRangeIds
              ? res.data.resourceRangeIds.split(",")
              : null,
            executionPolicyTime,
          });

          if (n === 1) {
            this.open = true;
            this.form.scanType = res.data.scanType.toString();
            this.title = "编辑任务";
          }
        } else {
          this.$GlobalErrorConfirm("数据加载失败", res.msg);
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.scanType = parseInt(this.form.scanType);

          // const restaskDbGroupPos = [];
          // this.resourceScope.map((v) => {
          //   this.form.restaskDbGroupPos.map((value) => {
          //     if (v.id == value) {
          //       restaskDbGroupPos.push({
          //         dbGroupTypeId: 0,
          //         dbGroupId: value,
          //       });
          //     }
          //   });
          // });

          const resetParams = {
            remark: undefined,
            updateTime: undefined,
            delFlag: undefined,
            checkFlag: undefined,
            createTime: undefined,
          };
          const params = Object.assign(
            {},
            this.form,
            {
              // restaskDbGroupPos: JSON.stringify(restaskDbGroupPos),
              executionPolicyType: 2, // 默认传2
              startTime: this.form.executionPolicyTime.length
                ? this.form.executionPolicyTime[0]
                : "",
              endTime: this.form.executionPolicyTime.length
                ? this.form.executionPolicyTime[1]
                : "",
              resourceRangeIds: this.form.resourceRangeIds.join(","),
            },
            resetParams
          );

          // console.log(params);
          if (this.form.executionCycleTypeId === 5) {
            if (
              +params.executionDay === 29 ||
              +params.executionDay === 30 ||
              +params.executionDay === 31
            ) {
              this.$confirm(
                "某些月份不足" +
                  params.executionDay +
                  "天，对于这些月份，扫描将被安排到该月的最后一天",
                "警告",
                {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning",
                }
              ).then(() => {
                this.handleAddOrEdit(params);
              });
            } else {
              this.handleAddOrEdit(params);
            }
          } else {
            this.handleAddOrEdit(params);
          }
        }
      });
    },

    changeRadio(val) {
      if (val === 1) this.form.lineNumber = null;
    },

    handleChange() {
      let nodeList = this.$refs["taskCascader"].getCheckedNodes(true);
      if (nodeList.length) {
        let restaskDbGroupPos = [];
        nodeList.forEach((item) => {
          restaskDbGroupPos.push(item.data.name);
        });
        this.form.restaskDbGroupPos = restaskDbGroupPos.join(",");
      }
    },

    handleAddOrEdit(params) {
      this.buttonLoading = true;
      if (this.form.executionPolicyId != null) {
        this.policyEdit(params);
      } else {
        this.policyAdd(params);
      }
    },

    policyEdit(params) {
      const nousePrams = {
        taskDbGroupPos: undefined,
        createUserCode: undefined,
        activeFlag: undefined,
        lastExecutionTime: undefined,
      };
      let re = {};
      if (this.form.executionCycleTypeId === 1) {
        re = {
          executionDay: undefined,
          executionTime: undefined,
        };
      }
      if (this.form.executionCycleTypeId === 2) {
        re = {
          executionDay: undefined,
        };
      }
      if (
        this.form.executionCycleTypeId === 3 ||
        this.form.executionCycleTypeId === 4 ||
        this.form.executionCycleTypeId === 5 ||
        this.form.executionCycleTypeId === 7
      ) {
        params.executionTime = params.executionTime.substr(0, 5);
      }
      updatePolicy(Object.assign({}, params, nousePrams, re))
        .then((res) => {
          if (res && res.code === 200) {
            this.$GlobalSuccessMessage("编辑成功");
            this.open = false;
            this.getList();
          } else {
            this.$GlobalErrorConfirm("编辑失败", res.msg);
          }
        })
        .finally(() => {
          this.buttonLoading = false;
        });
    },

    policyAdd(params) {
      addPolicy(params)
        .then((res) => {
          if (res && res.code === 200) {
            this.$GlobalSuccessMessage("新增成功");
            this.open = false;
            this.getList();
          } else {
            this.$GlobalErrorConfirm("新增失败", res.msg);
          }
        })
        .finally(() => {
          this.buttonLoading = false;
        });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let isStatus = false;
      this.policyList.map((item) => {
        if (
          (item.taskStatus === 0 &&
            this.ids.includes(item.executionPolicyId)) ||
          row.taskStatus === 0
        ) {
          isStatus = true;
        }
      });
      if (isStatus) {
        return this.$GlobalErrorConfirm("警告", "启用状态不允许删除");
      }

      const executionPolicyIds = row.executionPolicyId
        ? row.executionPolicyId
        : this.ids.join(",");

      this.$GlobalDeleteConfirm()
        .then(() => {
          delPolicy({ executionPolicyIds }).then((res) => {
            if (res && res.code === 200) {
              this.$GlobalSuccessMessage("删除成功");
              if (
                this.queryParams.pageNum > 1 &&
                executionPolicyIds.split(",").length === this.policyList.length
              ) {
                this.queryParams.pageNum -= 1;
              }
              this.getList();
            } else {
              this.$GlobalErrorConfirm("删除失败", res.msg);
            }
          });
        })
        .catch(() => {});
    },
    handleStop(status, row) {
      const ids = row?.executionPolicyId || this.ids.join(",");
      const text =
        (row && row.taskStatus === 0) || status === 1 ? "停用" : "启用";
      this.$confirm("是否确认" + text + "?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        setTaskStatus({
          executionPolicyIds: ids,
          taskStatus: text === "停用" ? 1 : 0,
        }).then((res) => {
          if (res && res.code === 200) {
            this.getList();
            this.$GlobalSuccessMessage(text + "成功");
            this.ids = [];
          } else {
            this.$GlobalErrorConfirm(text + "失败", res.msg);
          }
        });
      });
    },
    setCommand(command, row, type) {
      return {
        command: command ? command : null,
        data: row ? row : null,
        type: type ? type : null,
      };
    },
    handleCommand(command) {
      console.log(command.data);
      if (command.command === "edit") {
        this.handleUpdate(command.data, command.type);
      } else if (command.command === "change") {
        this.handleStop(null, command.data);
      } else if (command.command === "delete") {
        this.handleDelete(command.data);
      } else if (command.command === "detail") {
        this.viewDetail(command.data);
      } else if (command.command === "pauseContinues") {
        this.pauseContinues(command.data);
      }
    },
    pauseContinues(row) {
      let isPause = row.isPause === 2 ? 1 : 2;
      setPause({
        executionPolicyIds: row.executionPolicyId,
        isPause: isPause,
      }).then((res) => {
        if (res && res.code === 200) {
          this.$GlobalSuccessMessage("操作成功");
          this.getList();
        } else {
          this.$GlobalSuccessMessage("操作失败");
        }
      });
    },
    viewDetail(row) {
      console.log(row);
      row.deptName = row.deptId ? this.getDeptName(row.deptId) : "";
      row.executionCycle =
        this.executionCycleTypeFn(row.executionCycleTypeId) +
        ((row.executionDay || row.executionDay === 0) &&
        row.executionCycleTypeId === 5
          ? "/" + row.executionDay + "号"
          : "") +
        ((row.executionDay || row.executionDay === 0) &&
        row.executionCycleTypeId === 4
          ? "/" + this.dayArr[row.executionDay]
          : "") +
        (row.executionTime ? "/" + row.executionTime : "");

      this.$refs.policyDetail.show(row);
    },

    closeHistory() {
      this.isShowHistory = false;
    },
  },
};
</script>

<style scoped lang="scss">
.el-dropdown-link {
  color: var(--theme-color);
}
.add {
  ::v-deep .el-date-editor {
    width: 100%;
  }
}
</style>
